package com.hxzy.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class WeixinUtil {


    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;


    /**
     * 根据微信小程序的授权码换令牌
     * https://api.weixin.qq.com/sns/jscode2session?appid=自己的id&secret=自己的密码&js_code=临时授权码&grant_type=authorization_code*
     * @param code
     * @return
     */
    public String getOpenId(String code) throws JsonProcessingException {
        String url = "https://api.weixin.qq.com/sns/jscode2session";

        //构建post数据
        MultiValueMap<String, Object> postData = new LinkedMultiValueMap<>();
        postData.add("appid", appId);
        postData.add("secret", appSecret);
        postData.add("js_code", code);
        postData.add("grant_type", "authorization_code");

        //向微信服务器发送post请求
        RestTemplate restTemplate=new RestTemplate();

        String resultString = restTemplate.postForObject(url, postData, String.class);
        //序列化
        ObjectMapper objectMapper=new ObjectMapper();
        Map resultMap  = objectMapper.readValue(resultString, Map.class);

        // post请求，返回的结果：
        //  {"session_key":"eL1IRMgf4E4LndpzlvueFA==","openid":"ob61W5xhEqE-eipazDy1B1ZCM7mU"}
        Object openId = resultMap.get("openid");
        if (openId == null || openId.toString().isEmpty()) {
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId.toString();
    }


}
